package com.common.core.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;

/**
 * @auther zhangwj
 * @date 2021/12/20 下午4:56
 */
public class ResourceUtil {

    public static PropertySource<?> getPropertySource(String profile) {
        Resource resource = new ClassPathResource(profile);
        return loadProfiles(resource);
    }

    public static <T> T getJSONObject(Resource resource, Class<T> clazz) throws IOException {
        String jsonStr = getResource(resource);
        if (!StringUtils.hasText(jsonStr)) {
            return null;
        }
        return JSONObject.parseObject(jsonStr, clazz);
    }

    public <T> List<T> getJSONArray(Resource resource, Class<T> clazz) throws IOException {
        String jsonStr = getResource(resource);
        if (!StringUtils.hasText(jsonStr)) {
            return null;
        }
        return JSONArray.parseArray(jsonStr, clazz);
    }

    private static String getResource(Resource resource) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
        StringBuilder message = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            message.append(line);
        }
        return message.toString();
    }

    private static PropertySource<?> loadProfiles(Resource resource) {
        if (null == resource) {
            throw new NullPointerException("resource is null");
        }
        if (!resource.exists()) {
            throw new IllegalArgumentException("file" + resource + "not exist");
        }
        String name = resource.getFilename();
        if (!StringUtils.hasText(name)) {
            throw new NullPointerException("resource name is null");
        }
        try {
            Properties properties = new Properties();
            properties.load(resource.getInputStream());
            return new PropertiesPropertySource(name, properties);
        } catch (IOException ex) {
            throw new IllegalStateException("load resource exception" + resource, ex);
        }
    }
}
